from flask import Flask, render_template, request, redirect, url_for, session
from flask_socketio import SocketIO, send, emit, join_room, leave_room
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import secrets

app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_hex(16)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://gaojc:123456@localhost/caas'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
socketio = SocketIO(app)
db = SQLAlchemy(app)

# 数据库模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)

class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    room = db.Column(db.String(50), nullable=False)
    user = db.relationship('User', backref=db.backref('messages', lazy=True))

# 路由
@app.route('/')
def index():
    if 'username' in session:
        return redirect(url_for('chat'))
    return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    user = User.query.filter_by(username=username, password=password).first()
    if user:
        session['username'] = username
        return redirect(url_for('chat'))
    return '用户名或密码错误!', 401

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if User.query.filter_by(username=username).first():
            return '用户不存在!', 400
        new_user = User(username=username, password=password)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('register.html')

@app.route('/chat')
def chat():
    if 'username' not in session:
        return redirect(url_for('index'))
    return render_template('chat.html')

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

# SocketIO事件处理
@socketio.on('connect')
def handle_connect():
    username = session.get('username')
    if username:
        join_room('general')
        user = User.query.filter_by(username=username).first()
        emit('message', {'user': 'System', 'content': f'{username} 进入了聊天室', 'timestamp': datetime.utcnow().strftime('%H:%M:%S')}, room='general')

@socketio.on('disconnect')
def handle_disconnect():
    username = session.get('username')
    if username:
        leave_room('general')
        emit('message', {'user': 'System', 'content': f'{username} 离开了聊天室', 'timestamp': datetime.utcnow().strftime('%H:%M:%S')}, room='general')

@socketio.on('send_message')
def handle_message(data):
    username = session.get('username')
    if username and 'message' in data:
        user = User.query.filter_by(username=username).first()
        message = Message(content=data['message'], user_id=user.id, room='general')
        db.session.add(message)
        db.session.commit()
        emit('message', {'user': username, 'content': data['message'], 'timestamp': datetime.utcnow().strftime('%H:%M:%S')}, room='general')

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.debug = True
    socketio.run(app, host='0.0.0.0', port=5000,allow_unsafe_werkzeug=True)